package photorganizer.presentation.common.image;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import photorganizer.common.cache.Cache;

public class TwoLevelImageCache<K> implements Cache<K, BufferedImage> {

	public static final String FORMAT = "jpeg";

	private final Cache<K, BufferedImage> memoryCache;

	private final Cache<K, byte[]> persistentCache;

	public TwoLevelImageCache(Cache<K, BufferedImage> memoryCache, Cache<K, byte[]> persistentCache) {
		this.memoryCache = memoryCache;
		this.persistentCache = persistentCache;
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.cache.Cache#get(java.lang.Object)
	 */
	public BufferedImage get(K key) {
		BufferedImage result = memoryCache.get(key);
		if (result == null) {
			byte[] byteArray = persistentCache.get(key);
			if (result != null) {
				InputStream inputStream = new ByteArrayInputStream(byteArray);
				try {
					result = ImageIO.read(inputStream);
				}
				catch (IOException e) {
					// TODO handle IOException
				}
				memoryCache.put(key, result);
			}
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.cache.Cache#put(java.lang.Object, java.lang.Object)
	 */
	public void put(K key, BufferedImage image) {
		memoryCache.put(key, image);
		ByteArrayOutputStream outputSteam = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, FORMAT, outputSteam);
		}
		catch (IOException e) {
			// TODO handle IOException
		}
		persistentCache.put(key, outputSteam.toByteArray());
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.cache.Cache#remove(java.lang.Object)
	 */
	public void remove(K key) {
		memoryCache.remove(key);
		persistentCache.remove(key);
	}

	/* (non-Javadoc)
	 * @see photorganizer.common.lifecycle.Closeable#close()
	 */
	public void close() {
		memoryCache.close();
		persistentCache.close();
	}

}
